"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const path_1 = tslib_1.__importDefault(require("path"));
const miniprogram_ci_1 = require("miniprogram-ci");
const cli_table3_1 = tslib_1.__importDefault(require("cli-table3"));
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const ora_1 = tslib_1.__importDefault(require("ora"));
const util_1 = require("./util");
function fsExistsSync(path) {
    try {
        // @ts-ignore
        fs_1.default.accessSync(path, fs_1.default.F_OK);
    }
    catch (e) {
        return false;
    }
    return true;
}
class Ci {
    constructor(opts) {
        this.workspace = '';
        const { workspace, type, version, desc, pkp, env, robot } = opts;
        this.workspace = workspace;
        this.version = version;
        this.desc = desc;
        this.env = env;
        this.robot = robot;
        // 加载配置文件
        if (this.loadProjectConfig(path_1.default.join(workspace, 'project.config.json')) && this.projectConfig) {
            this.project = new miniprogram_ci_1.Project({
                appid: this.projectConfig.appid,
                type: type,
                projectPath: workspace,
                privateKeyPath: pkp,
                ignores: ['node_modules/**/*'],
            });
        }
    }
    loadProjectConfig(configPath) {
        if (this.isFileExist(configPath)) {
            try {
                const jsonString = fs_1.default.readFileSync(configPath);
                const config = JSON.parse(jsonString.toString());
                this.projectConfig = {
                    appid: config.appid,
                    miniprogramRoot: config.miniprogramRoot,
                    setting: config.setting,
                    compileType: config.compileType,
                };
                return true;
            }
            catch (error) {
                console.log(chalk_1.default.red('Load file failed'));
                console.log(chalk_1.default.red(error));
                return false;
            }
        }
        return false;
    }
    isFileExist(file) {
        return fsExistsSync(file);
    }
    getTitleFromGit() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let version = this.version || process.env.npm_package_version || '';
            let desc = this.desc;
            let envDesc = this.env ? `env: ${this.env}` : '';
            if (!version) {
                try {
                    // eslint-disable-next-line global-require,import/no-dynamic-require
                    const pkg = require(path_1.default.resolve(this.workspace, 'package.json'));
                    version = pkg.version;
                }
                catch (error) {
                    version = '0.0.0';
                    console.error(chalk_1.default.red('Load package.json failed'));
                    console.error(chalk_1.default.red(error));
                }
            }
            try {
                const latestCommit = yield util_1.getLastCommitLog(this.workspace);
                const hash = `(${latestCommit.hash.substring(0, 7)})`;
                if (this.env) {
                    version = `${version}.${this.env}`;
                }
                // 没有desc时使用提交信息
                desc = `${envDesc} ${desc || latestCommit.message + hash}`;
            }
            catch (e) {
                if (this.env) {
                    version = `${version}.${this.env}`;
                }
                desc = `${envDesc} ${this.desc}`;
            }
            return {
                version,
                desc,
            };
        });
    }
    printResult(version, desc, result) {
        const { subPackageInfo = [], pluginInfo = [], devPluginId = '无' } = result;
        const table = new cli_table3_1.default({
            head: ['时间', '版本号', '项目备注'],
        });
        table.push([new Date().toLocaleString(), version, desc]);
        console.log(table.toString());
        console.log('包信息');
        const packageTable = new cli_table3_1.default({
            head: ['类型', '大小'],
        });
        subPackageInfo.forEach(packageInfo => {
            const formatSize = util_1.getFormatFileSize(packageInfo.size);
            packageTable.push([util_1.getPackageName(packageInfo.name), formatSize.size + formatSize.measure]);
        });
        console.log(packageTable.toString());
        if (pluginInfo && pluginInfo.length) {
            console.log('插件信息');
            const pluginTable = new cli_table3_1.default({
                head: ['appid', '版本', '大小', 'devPluginId'],
            });
            pluginInfo.forEach(pluginInfo => {
                const formatSize = util_1.getFormatFileSize(pluginInfo.size);
                pluginTable.push([pluginInfo.pluginProviderAppid, pluginInfo.version, formatSize.size + formatSize.measure, devPluginId]);
            });
            console.log(pluginTable.toString());
        }
    }
    relsoveQrPath(qrcodeFormat, qrcodeOutputDest) {
        if (qrcodeFormat === 'base64' || qrcodeFormat === 'image') {
            return path_1.default.join(this.workspace, qrcodeOutputDest || 'preview.png');
        }
        return '';
    }
    upload(opts) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (this.project) {
                const info = yield this.getTitleFromGit();
                const spinner = ora_1.default('上传...').start();
                try {
                    const uploadResult = yield miniprogram_ci_1.upload({
                        project: this.project,
                        version: info.version,
                        desc: info.desc,
                        setting: this.projectConfig ? this.projectConfig.setting : {},
                        onProgressUpdate: function () { },
                        // @ts-ignore
                        proxy: opts.proxy || '',
                        robot: this.robot,
                    });
                    spinner.succeed('上传成功');
                    this.printResult(info.version, info.desc, uploadResult);
                }
                catch (error) {
                    spinner.fail('上传失败');
                    console.error(chalk_1.default.red(error));
                    process.exit(1);
                }
            }
        });
    }
    preview(opts) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (this.project) {
                const info = yield this.getTitleFromGit();
                const spinner = ora_1.default('预览..').start();
                try {
                    const previewResult = yield miniprogram_ci_1.preview({
                        project: this.project,
                        version: info.version,
                        desc: info.desc,
                        setting: this.projectConfig ? this.projectConfig.setting : {},
                        qrcodeFormat: opts.qr,
                        qrcodeOutputDest: this.relsoveQrPath(opts.qr, opts.qrDest),
                        onProgressUpdate: function () { },
                        pagePath: opts.pagePath,
                        searchQuery: opts.searchQuery,
                        // @ts-ignore
                        proxy: opts.proxy || '',
                        robot: this.robot,
                    });
                    spinner.succeed('预览成功');
                    this.printResult(info.version, info.desc, previewResult);
                }
                catch (e) {
                    spinner.fail('预览失败');
                    console.error(chalk_1.default.red(e.message));
                    process.exit(1);
                }
            }
        });
    }
}
module.exports = Ci;
